package com.t2two.example.common.utils;

import cn.hutool.crypto.asymmetric.SM2;
import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.Security;

/**
 * @version 1.0
 * @description: TODO
 * @author: lifei
 * @date: 2025/2/17 11:05
 */
public class SM2DoubleDecryptUtil {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    // 网关提供的二次核验私钥（示例）
//    private static final String GATEWAY_PRIVATE_KEY = "替换为图2中的私钥";

//    @Value("${sm2.privateKeyHex}")
//    private static String privateKeyHex;
    // 业务方固定私钥
    private static final String BUSINESS_PRIVATE_KEY = "3c57e96dac2d6d0dfd92e400ebb609e584b148b755968d898bd25f226aa5b636";

    /**
     * 完整解密流程
     * @param interfaceToken 加密令牌
     * @return 解密后的JSON数据
     */
    public static String decryptInterfaceToken(String interfaceToken,String privateKeyHex) {
        try {
            // 第一次解密：使用网关私钥
            byte[] firstDecrypted = decrypt(Hex.decode(interfaceToken), privateKeyHex);
            System.out.println("444444444444444444444 "+ JSONObject.toJSONString(firstDecrypted));
            // 第二次解密：使用业务私钥
            byte[] secondDecrypted = decrypt(firstDecrypted, BUSINESS_PRIVATE_KEY);

            return new String(secondDecrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }

    /**
     * 单次解密方法
     * @param cipherData 密文数据
     * @param privateKeyHex 私钥HEX
     */
    private static byte[] decrypt(byte[] cipherData, String privateKeyHex) {
        try {
            System.out.println("密文长度: " + cipherData.length);
            System.out.println("密文Hex: " + Hex.toHexString(cipherData));
            X9ECParameters ecParams = GMNamedCurves.getByName("sm2p256v1");
            ECDomainParameters domainParams = new ECDomainParameters(
                    ecParams.getCurve(),
                    ecParams.getG(),
                    ecParams.getN(),
                    ecParams.getH()
            );
            System.out.println("aaaaaaaaaaaaaaaaaaaa "+JSONObject.toJSONString(ecParams));
            // 加载私钥（自动补全64位）
            String fullPrivateKey = String.format("%64s", privateKeyHex).replace(' ', '0');
            System.out.println("uuuuuuuuuuuuuuuuuuuuuu "+(fullPrivateKey));
            BigInteger privateKey = new BigInteger(fullPrivateKey, 16);
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaa "+(privateKey));
            ECPrivateKeyParameters privateKeyParams = new ECPrivateKeyParameters(privateKey, domainParams);

            SM2Engine engine = new SM2Engine(SM2Engine.Mode.C1C2C3);
            engine.init(true, privateKeyParams);

            return engine.processBlock(cipherData, 0, cipherData.length);
        } catch (Exception e) {
            throw new RuntimeException("解密阶段失败", e);
        }
    }


    // 示例数据验证
    public static void main(String[] args) {
        String sampleToken = "04ac5724c05b8a145abbc7afdcc0766565971bb307d6da93ba4bd735fe1addfef3a58b37aa3238c52c1efdc1add84e3e63f06516967feca19496c24f643381c62a64722ff549485a72b1216b98db0521d807c29a14d663af76c92c30e06336d8f447e5b7ddf68a695ed38d6825e2d1face2101143c06cea26a56a77de3fe61373c67a4c72fc4fb53cf3881e9b6164dd966b30b9f1e6417caa906728d7ce26504066f3b279d442526a854f426bc06e4fda69a968ad69b59acc915092dacff62dd34b65111b8883f3d1e722aa063812f5830bc0df32587e458ea739a6cf0a24d4e90c3e045d49a3b103f586ae61d640b72f7e69169a9cf2a1499f2aa391a6fcd5c7755f1fef61346ced2087ab9a1527a85d93eefbc527d43c5f8ba648cb02220e188d31e4a7ed89bb4d94b3abe31c2a83985b4603374b39561cd96d944ea3d45c54f1cb03ea318365b05b70f83c461f0b55cf956b3121389874f66760761f0e2a4dc9ac89e79bf8fdcc6e2e4ecf39bf8a49fc40b6e0dea0e65900d0f4e9fa912c1c84e99133a77eaff3b5fdceb5e587fde3e3dc6c20cb3bc4a9223f4e4e2d904d546ee42c3cfabb9902d938ce2b6d0d5961ab119968e287d774a87f09cd7175bf2e93a5ee9bf002965c73ac31c79eee0f057c93bab2da5824adb065a8fa7205074d27b9d371248d7a89be51fea3c0f9eec92790c335e0185c18b2513c925f679f59443ffa3eeb8715e86cacdf451f2485041f6cbebaa0fa49e3ce8efcc9d771647a101f991dff77de1cedaf06f56c17dc02adb2974249a34a852920568d1d9455488f5a19b347d0700cc0f7313adb5b65a344fbc7066cd3809e44416fe60128389cb3194de5fcdf44bb6535b4761788e8bd9d9a62fbbcc0224e079d1b0b987cb7dbfc4a4ccf64f705ea872b70c958caf1c4bb5929a62a9747d105be91a43ef1341e571a2eb4cbdcba88f5fed7e4493f16b88bbae1739dec375f9e053d2ddfc2e53e8aca17d6ca68ac5106342b4098c7396adb45fcc9a7f3d3c8a40c183f31a6ad0c9774b3a5a285b65dc1d53a8df76ed0c9f7aba8a55e306adcf93666385498513546af9ad9da241bbb5d42ba813350c89e877614d435297a0f81322cd0c1d6a3a7e155d98a1fcc5466695aca14e2d0bd59008c6031719631e3a300daff7b80a6ba6f3dad08f81455ee72a0e60921e158bbec2e498ee80744483ef375862d69ec0a2983b14a59637f12cded8b6c942774e01f8c0855e98baadeae4db321e29d6e6f15b3c1d6b8d81d25fad988774";
        String result = decryptInterfaceToken(sampleToken,"16cf62248840bf5d94c54502019606be14607167af43ff5d11d7b20e6407c2ff");
        System.out.println("解密结果：" + result);
    }

    public static String sm2Decrypt(String privateKey,String cipherText){
        SM2 sm2 = new SM2(null,privateKey);
//        sm2.decryptStr(cipherText, KeyType.);z
        return null;
    }
}
